package components
{
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import mx.controls.Button;
	import mx.controls.Label;
	import mx.controls.RichTextEditor;
	import mx.events.ResizeEvent;
	
	import nl.wv.extenders.panel.SuperPanel;
	
	import tools.*;
	
	public class NewReply{
		private var panel:SuperPanel = new SuperPanel();
		private var newReplyBtn:Button = new Button();
		private var tekstEditor:RichTextEditor = new RichTextEditor();
		private var service:Mysql = new Mysql();
		private var tool:Tool = new Tool();
		private var labela:Label = new Label();
		
		private var username:String;
		private var tema:String;
		private var naziv:String;
		
		public function NewReply(p:SuperPanel){
			panel = p;
			panel.addEventListener(ResizeEvent.RESIZE, onResize);
			newReplyBtn.label = "ODGOVORI";
			newReplyBtn.x = panel.width-112;
			newReplyBtn.y = panel.height-45;
			newReplyBtn.addEventListener(MouseEvent.CLICK, onNewReplyBtnClick);
			labela.x=10;
			labela.y=20;
			tekstEditor.x = 10;
			tekstEditor.y = 35;
	 		tekstEditor.height=panel.height-86;
	 		tekstEditor.width=panel.width-30;
			tekstEditor.title="Unesite vas tekst ovdje: ";
			p.addChild(newReplyBtn);
			p.addChild(tekstEditor);
			p.addChild(labela);
		}
		
		public function setParameters(u:String, t:String, n:String):void{
			username = u;
			tema = t;
			naziv = n;
			labela.htmlText = "Odgovorite na temu <b>\""+naziv+"\"</b>:";
		}
		
		public function onNewReplyBtnClick(e:Event):void{
		if(tekstEditor.text.length>0){
			var help:String=tekstEditor.htmlText;
			if(tool.checkForCRC(help)){
				tool.createAlert("Greska!", "Rijec 'CRC' se ne smije nalaziti u tekstu!", 200);
			} else {			
				help=tool.CodeTekst(tekstEditor.htmlText);
            	service.sql = {type:"INSERT", into:"komentar", columns:"tekst, datum, vrijeme, tema, username", values:"@"+help+"@,@"+tool.currentDate()+"@,@"+tool.currentTime()+"@,@"+tema+"@,@"+username+"@"}; 
				service.addEventListener(service.MYSQL_RESULT, onResult);
 				service.startService();
 			}
 		} else tool.createAlert("Greska!", "Morate unijeti tekst!", 200);
		}
		
		public function onResult(e:Event):void{
			if(service.xml.results.result){
				tool.createAlert("Info", "Odgovor je uspjesno upisan!\nOtvorite ponovo prozor sa temom da bi vidjeli odgovor!", 200);
				panel.closePanel();
			} else tool.createAlert("Info", "Pri slanju odgovora dogodila se greska, pokusajte ponovo!", 200);
		}
		
		public function onResize(e:Event):void{
			newReplyBtn.x = panel.width-112;
			newReplyBtn.y = panel.height-45;
	 		tekstEditor.height=panel.height-86;
	 		tekstEditor.width=panel.width-30;
		}
	}
}